package com.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 描述:
 *
 * @author luzhongfu
 * Created by lucky on 2020-06-01 1:39 PM
 */
public class MySemaphore {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        for (int i =1; i < 5 ; i ++){
            executorService.execute(new SemaphoreThread(semaphore,i + 5));
        }
        executorService.shutdown();
    }

    static class SemaphoreThread implements Runnable{

        private Semaphore semaphore;

        private int x;

        public SemaphoreThread(Semaphore semaphore, int x) {
            this.semaphore = semaphore;
            this.x = x;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire(x);
                System.out.println("使用了x"+x);

            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release(x);
                System.out.println("释放了x"+x);
            }
        }
    }
}
